package Model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.sql.Date;

/* This object is meant to encapsulate and simplify the procedure for converting Strings
 *  into dates. 
 */
public class ParseStringToDate {
	//Static Date Format object
	private static SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-M-d");

	//Fields of this object and their getters (read only)
	private Calendar thisDate;
	//Return clone as object should be read only
	public Calendar getThisDate()
	{ 
		if (thisDate == null)
		{ return null; }
		else 
		{ return (Calendar) thisDate.clone(); }
	}
	public Date getThisDateAsSQL()
	{
		if (thisDate == null)
		{ return null; }
		else
		{ return new Date( thisDate.getTimeInMillis() ); }
	}
	public int getThisDateDayOfWeek()
	{
		if (thisDate == null)
		{ return -1; }
		else
		{ return thisDate.get(Calendar.DAY_OF_WEEK); }
	}
	
	private String errorMsg;
	public String getErrorMsg()
	{ return errorMsg; }
	
	//Constructor MUST take in String
	public ParseStringToDate(String input) 
	{
		if ( checkFormat(input) ) {					//Check format is correct
			java.util.Date tempD = null;
			ParseException error = null;
			try {
				 tempD = sdFormat.parse(input);	//Try to parse string
			} catch (ParseException e) {
				error = e;
			}
			if (tempD == null) {							//If parsing failed
				errorMsg = error.getMessage();	//Extract Error message
				thisDate = null;				
			} else {											//Otherwise parsing succeeded
				errorMsg = "";								//No error Message
				thisDate = Calendar.getInstance();
				thisDate.setTime(tempD);				//Save as Calendar
			}
		} else {												//Otherwise format is wrong
			errorMsg = "Date must be in " + sdFormat.toPattern() + " format";
			thisDate = null;
		}
	}
	
	//Miscellaneous Methods
	public String toString() 
	{
		if ( thisDate == null )
		{ return errorMsg; }
		else
		{ return (sdFormat.format( thisDate.getTime() ) ); }
	}
	
	private static boolean checkFormat (String input)
	{
		if ( input.matches("[0-9]{4}-[0-9]+-[0-9]+") )
		{ return true; }
		else
		{return false; }
	}
	
}
